import { ref, reactive, computed, onMounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import organizationApi, { type OrganizationListItem } from "@/api/system/org/organization";
import memberApi, { type OrgMemberItem } from "@/api/system/org/member";
import auditApi, { type OrgAuditItem } from "@/api/system/org/audit";
import { fetchRegionTree } from "@/api/system/region/region";
import type { TableColumnList } from "@pureadmin/table";

interface PaginationState {
  currentPage: number;
  pageSize: number;
  total: number;
  layout?: string;
  align?: string;
  background?: boolean;
  size?: string;
}

interface OrganizationFilterForm {
  keyword: string;
  org_type: string | number;
  status: string | number;
  region_id: string | number;
}

export function useOrganizationCenter() {
  const orgTableRef = ref();
  const regionTree = ref<any[]>([]);
  const route = useRoute();
  const router = useRouter();

  const detectTab = (path: string, query: Record<string, any>): "org" | "audit" =>
    query.view === "audit" || path.includes("/system/user/org-audit")
      ? "audit"
      : "org";

  const isSameQuery = (nextQuery: Record<string, any>) => {
    const current = route.query as Record<string, any>;
    const nextKeys = Object.keys(nextQuery);
    const currentKeys = Object.keys(current);
    if (nextKeys.length !== currentKeys.length) return false;
    return nextKeys.every(key => String(nextQuery[key]) === String(current[key]));
  };

  const activeListTab = ref<"org" | "audit">(
    detectTab(route.path, route.query as Record<string, any>)
  );

  const orgFilter = reactive<OrganizationFilterForm>({
    keyword: "",
    org_type: "",
    status: "",
    region_id: ""
  });

  const orgPagination = reactive<PaginationState>({
    currentPage: 1,
    pageSize: 10,
    total: 0,
    layout: "total, sizes, prev, pager, next, jumper",
    align: "right",
    background: true,
    size: "default"
  });

  const orgLoading = ref(false);
  const orgList = ref<OrganizationListItem[]>([]);

  const orgColumns = computed<TableColumnList>(() => [
    {
      label: "组织名称",
      prop: "name",
      minWidth: 200
    },
    {
      label: "组织类型",
      slot: "org_type",
      width: 120
    },
    {
      label: "区域",
      slot: "region",
      width: 160
    },
    {
      label: "状态",
      slot: "status",
      width: 110
    },
    {
      label: "邀请人",
      prop: "inviter_name",
      minWidth: 140
    },
    {
      label: "邀请人ID",
      prop: "invited_by",
      width: 120
    },
    {
      label: "创建时间",
      prop: "create_time",
      width: 180
    },
    {
      label: "操作",
      slot: "operation",
      width: 200,
      fixed: "right"
    }
  ]);

  const statusTagType = (status?: number) => {
    switch (status) {
      case 1:
        return "success";
      case 2:
        return "danger";
      default:
        return "warning";
    }
  };

  const organizationDrawerVisible = ref(false);
  const currentOrganization = ref<OrganizationListItem | null>(null);

  const auditTableRef = ref();
  const auditFilter = reactive({
    keyword: "",
    org_type: "",
    region_id: ""
  });
  const auditPagination = reactive<PaginationState>({
    currentPage: 1,
    pageSize: 10,
    total: 0,
    layout: "total, sizes, prev, pager, next, jumper",
    align: "right",
    background: true,
    size: "default"
  });
  const pendingAuditLoading = ref(false);
  const auditList = ref<OrgAuditItem[]>([]);
  const auditDetailVisible = ref(false);
  const selectedAuditRecord = ref<OrgAuditItem | null>(null);
  const auditInitialized = ref(false);

  const flatRegionOptions = computed(() => {
    const options: Array<{ value: number; label: string }> = [];
    const traverse = (items: any[]) => {
      items.forEach(item => {
        options.push({
          value: item.id,
          label: item.full_path ?? item.path ?? item.label ?? item.name ?? `区域 ${item.id}`
        });
        if (Array.isArray(item.children) && item.children.length) {
          traverse(item.children);
        }
      });
    };
    traverse(regionTree.value ?? []);
    return options;
  });

  const auditColumns = computed<TableColumnList>(() => [
    {
      label: "企业名称",
      prop: "display_name",
      minWidth: 220
    },
    {
      label: "手机号",
      prop: "phone",
      width: 140
    },
    {
      label: "邀请人",
      slot: "inviter",
      minWidth: 160
    },
    {
      label: "区域",
      slot: "region",
      minWidth: 160
    },
    {
      label: "提交时间",
      prop: "submitted_at",
      width: 180
    },
    {
      label: "状态",
      slot: "audit_status",
      width: 110
    },
    {
      label: "操作",
      slot: "audit_operation",
      width: 220,
      fixed: "right"
    }
  ]);

  const buildOrgParams = () => {
    const params: Record<string, any> = {
      page: orgPagination.currentPage,
      page_size: orgPagination.pageSize
    };
    if (orgFilter.keyword) params.keyword = orgFilter.keyword;
    if (orgFilter.org_type) params.org_type = orgFilter.org_type;
    if (orgFilter.status !== "" && orgFilter.status !== null)
      params.status = orgFilter.status;
    if (orgFilter.region_id) params.region_id = orgFilter.region_id;
    return params;
  };

  const fetchOrganizations = async () => {
    orgLoading.value = true;
    try {
      const result = await organizationApi.fetchList(buildOrgParams());
      orgList.value = result.list;
      orgPagination.total = result.pagination.total;
      orgPagination.currentPage = result.pagination.currentPage;
      orgPagination.pageSize = result.pagination.pageSize;
    } catch (error: any) {
      message(error?.message ?? "获取组织列表失败", { type: "error" });
    } finally {
      orgLoading.value = false;
    }
  };

  const handleOrgSearch = async () => {
    orgPagination.currentPage = 1;
    await fetchOrganizations();
  };

  const handleOrgReset = async () => {
    orgFilter.keyword = "";
    orgFilter.org_type = "";
    orgFilter.status = "";
    orgFilter.region_id = "";
    await handleOrgSearch();
  };

  const handleOrgPageChange = async (page: number) => {
    orgPagination.currentPage = page;
    await fetchOrganizations();
  };

  const handleOrgPageSizeChange = async (size: number) => {
    orgPagination.pageSize = size;
    orgPagination.currentPage = 1;
    await fetchOrganizations();
  };

  const selectOrganization = (record: OrganizationListItem | null) => {
    if (!record) {
      currentOrganization.value = null;
      organizationDrawerVisible.value = false;
      return;
    }
    currentOrganization.value = record;
    organizationDrawerVisible.value = true;
  };

  const closeOrganizationDetail = () => {
    currentOrganization.value = null;
    organizationDrawerVisible.value = false;
  };

  const buildAuditParams = () => {
    const params: Record<string, any> = {
      page: auditPagination.currentPage,
      page_size: auditPagination.pageSize,
      status: 0
    };
    if (auditFilter.keyword) params.keyword = auditFilter.keyword;
    if (auditFilter.org_type) params.org_type = auditFilter.org_type;
    if (auditFilter.region_id) params.region_id = auditFilter.region_id;
    return params;
  };

  const fetchAuditList = async () => {
    pendingAuditLoading.value = true;
    try {
      const result = await auditApi.fetchList(buildAuditParams());
      auditList.value = result.list;
      auditPagination.total = result.pagination.total;
      auditPagination.currentPage = result.pagination.currentPage;
      auditPagination.pageSize = result.pagination.pageSize;
    } catch (error: any) {
      ElMessage.error(error?.message ?? "获取待审核企业失败");
    } finally {
      pendingAuditLoading.value = false;
    }
  };

  const handleAuditSearch = async () => {
    auditPagination.currentPage = 1;
    await fetchAuditList();
  };

  const handleAuditReset = async () => {
    auditFilter.keyword = "";
    auditFilter.org_type = "";
    auditFilter.region_id = "";
    await handleAuditSearch();
  };

  const handleAuditPageChange = async (page: number) => {
    auditPagination.currentPage = page;
    await fetchAuditList();
  };

  const handleAuditPageSizeChange = async (size: number) => {
    auditPagination.pageSize = size;
    auditPagination.currentPage = 1;
    await fetchAuditList();
  };

  const auditStatusTagType = (status?: number) => {
    switch (status) {
      case 1:
        return "success";
      case 2:
        return "danger";
      default:
        return "warning";
    }
  };

  const openAuditDetail = (record: OrgAuditItem) => {
    selectedAuditRecord.value = record;
    auditDetailVisible.value = true;
  };

  const closeAuditDetail = () => {
    auditDetailVisible.value = false;
    selectedAuditRecord.value = null;
  };

  const refreshAfterAuditChange = async () => {
    if (auditInitialized.value) {
      await fetchAuditList();
    }
    await fetchOrganizations();
  };

  const approveAuditRecord = async (record: OrgAuditItem) => {
    try {
      await auditApi.approve(record.user_id, record.type, record.region?.id ? { region_id: record.region.id } : {});
      ElMessage.success("审核已通过");
      if (selectedAuditRecord.value?.audit_id === record.audit_id) {
        closeAuditDetail();
      }
      await refreshAfterAuditChange();
    } catch (error: any) {
      ElMessage.error(error?.message ?? "审核通过失败");
    }
  };

  const rejectAuditRecord = async (record: OrgAuditItem) => {
    try {
      const { value, action } = await ElMessageBox.prompt("请输入驳回原因", "驳回审核", {
        inputPattern: /.+/,
        inputErrorMessage: "驳回原因不能为空",
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      });
      if (action !== "confirm") return;
      await auditApi.reject(record.user_id, record.type, value);
      ElMessage.success("已驳回审核");
      if (selectedAuditRecord.value?.audit_id === record.audit_id) {
        closeAuditDetail();
      }
      await refreshAfterAuditChange();
    } catch (error: any) {
      if (error === "cancel") {
        return;
      }
      ElMessage.error(error?.message ?? "审核驳回失败");
    }
  };

  const removeOrganization = async (organization?: OrganizationListItem | null) => {
    if (!organization) return;
    try {
      await ElMessageBox.confirm(
        `确认删除组织「${organization.name}」吗？`,
        "删除组织",
        {
          type: "warning",
          confirmButtonText: "删除",
          cancelButtonText: "取消"
        }
      );
    } catch {
      return;
    }

    try {
      await organizationApi.remove(organization.id);
      ElMessage.success("组织已删除");
      if (currentOrganization.value?.id === organization.id) {
        closeOrganizationDetail();
      }
      await fetchOrganizations();
    } catch (error: any) {
      ElMessage.error(error?.message ?? "删除组织失败");
    }
  };

  const quickCreateVisible = ref(false);
  const openQuickCreate = () => {
    quickCreateVisible.value = true;
  };

  const handleQuickCreateSuccess = async (organization: OrganizationListItem | null) => {
    quickCreateVisible.value = false;
    await fetchOrganizations();
    if (auditInitialized.value) {
      await fetchAuditList();
    }
    if (!organization) {
      return;
    }
    const matched =
      orgList.value.find(item => item.id === organization.id) ??
      orgList.value.find(item => item.name === organization.name);
    if (matched) {
      selectOrganization(matched);
    }
  };

  // 组织编辑模态
  const organizationModalVisible = ref(false);
  const organizationModalMode = ref<"create" | "edit">("create");
  const editingOrganization = ref<OrganizationListItem | null>(null);

  const openCreateOrganization = () => {
    openQuickCreate();
  };

  const openEditOrganization = (organization?: OrganizationListItem | null) => {
    if (!organization) return;
    organizationModalMode.value = "edit";
    editingOrganization.value = organization;
    organizationModalVisible.value = true;
  };

  const handleOrganizationModalSuccess = async () => {
    organizationModalVisible.value = false;
    editingOrganization.value = null;
    await fetchOrganizations();
    if (currentOrganization.value) {
      const refreshed = orgList.value.find(item => item.id === currentOrganization.value?.id);
      if (refreshed) selectOrganization(refreshed);
    }
  };

  // 成员数据
  const membersLoading = ref(false);
  const memberList = ref<OrgMemberItem[]>([]);
  const memberPagination = reactive<PaginationState>({
    currentPage: 1,
    pageSize: 10,
    total: 0,
    layout: "total, prev, pager, next",
    align: "right",
    background: true,
    size: "small"
  });

  const memberColumns = computed<TableColumnList>(() => [
    { label: "成员用户ID", prop: "user_id", width: 120 },
    { label: "成员角色", prop: "member_role", width: 120 },
    { label: "职位", prop: "position", minWidth: 120 },
    { label: "状态", slot: "status", width: 120 },
    { label: "加入时间", prop: "joined_at", width: 160 },
    { label: "操作", slot: "operation", width: 160, fixed: "right" }
  ]);

  const fetchMembers = async () => {
    if (!currentOrganization.value) {
      memberList.value = [];
      memberPagination.total = 0;
      return;
    }
    membersLoading.value = true;
    try {
      const result = await memberApi.fetchList({
        org_id: currentOrganization.value.id,
        page: memberPagination.currentPage,
        page_size: memberPagination.pageSize
      });
      memberList.value = result.list;
      memberPagination.total = result.pagination.total;
      memberPagination.currentPage = result.pagination.currentPage;
      memberPagination.pageSize = result.pagination.pageSize;
    } catch (error: any) {
      ElMessage.error(error?.message ?? "获取组织成员失败");
    } finally {
      membersLoading.value = false;
    }
  };

  const handleMemberPageChange = async (page: number) => {
    memberPagination.currentPage = page;
    await fetchMembers();
  };

  const handleMemberPageSizeChange = async (size: number) => {
    memberPagination.pageSize = size;
    memberPagination.currentPage = 1;
    await fetchMembers();
  };

  const memberModalVisible = ref(false);
  const memberModalMode = ref<"create" | "edit">("create");
  const editingMember = ref<OrgMemberItem | null>(null);

  const openMemberDialog = (member?: OrgMemberItem | null) => {
    memberModalMode.value = member ? "edit" : "create";
    editingMember.value = member ?? null;
    memberModalVisible.value = true;
  };

  const handleMemberModalSuccess = async () => {
    memberModalVisible.value = false;
    editingMember.value = null;
    await fetchMembers();
  };

  const deleteMember = async (member: OrgMemberItem) => {
    try {
      await ElMessageBox.confirm(
        `确认移除成员 ${member.user_id} 吗？`,
        "移除成员",
        {
          type: "warning",
          confirmButtonText: "移除",
          cancelButtonText: "取消"
        }
      );
    } catch {
      return;
    }

    try {
      await memberApi.remove(member.id);
      ElMessage.success("成员已移除");
      await fetchMembers();
    } catch (error: any) {
      ElMessage.error(error?.message ?? "移除成员失败");
    }
  };

  // 审核记录
  const auditRecordLoading = ref(false);
  const auditRecords = ref<OrgAuditItem[]>([]);

  const loadAuditRecords = async () => {
    if (!currentOrganization.value) {
      auditRecords.value = [];
      return;
    }
    auditRecordLoading.value = true;
    try {
      const result = await auditApi.fetchList({
        keyword: currentOrganization.value.name,
        page: 1,
        page_size: 10
      });
      auditRecords.value = result.list.filter(item => {
        if (!currentOrganization.value) return false;
        return (
          item.org?.id === currentOrganization.value.id ||
          item.invited_by === currentOrganization.value.invited_by ||
          item.display_name === currentOrganization.value.name
        );
      });
    } catch (error: any) {
      ElMessage.error(error?.message ?? "获取审核记录失败");
    } finally {
      auditRecordLoading.value = false;
    }
  };

  const handleAuditApprove = async () => {
    if (!currentOrganization.value) return;
    const target = auditRecords.value.find(item => item.status === 0);
    if (!target) {
      ElMessage.warning("当前无待审核记录");
      return;
    }
    try {
      await auditApi.approve(target.user_id, target.type);
      ElMessage.success("审核已通过");
      await loadAuditRecords();
      await fetchOrganizations();
    } catch (error: any) {
      ElMessage.error(error?.message ?? "审核通过失败");
    }
  };

  const handleAuditReject = async () => {
    if (!currentOrganization.value) return;
    const target = auditRecords.value.find(item => item.status === 0);
    if (!target) {
      ElMessage.warning("当前无待审核记录");
      return;
    }
    try {
      await auditApi.reject(target.user_id, target.type, "驳回");
      ElMessage.success("已驳回审核");
      await loadAuditRecords();
      await fetchOrganizations();
    } catch (error: any) {
      ElMessage.error(error?.message ?? "审核驳回失败");
    }
  };

  const loadRegions = async () => {
    regionTree.value = await fetchRegionTree().catch(() => []);
  };

  const handleOrgRowClick = (row: OrganizationListItem) => {
    selectOrganization(row);
  };

  watch(currentOrganization, async value => {
    if (!value) {
      memberList.value = [];
      auditRecords.value = [];
      return;
    }
    memberPagination.currentPage = 1;
    await fetchMembers();
    await loadAuditRecords();
  });

  watch(activeListTab, async value => {
    if (value === "audit" && !auditInitialized.value) {
      auditInitialized.value = true;
      await fetchAuditList();
    }
    const targetPath = "/system/user/org-list";
    const nextQuery = { ...(route.query as Record<string, any>) };
    if (value === "audit") {
      nextQuery.view = "audit";
    } else {
      delete nextQuery.view;
    }
    if (route.path !== targetPath || !isSameQuery(nextQuery)) {
      router.replace({ path: targetPath, query: nextQuery }).catch(() => {});
    }
  }, { immediate: true });

  watch(
    () => [route.path, route.query],
    ([path, query]) => {
      const nextTab = detectTab(path as string, query as Record<string, any>);
      if (activeListTab.value !== nextTab) {
        activeListTab.value = nextTab;
      }
    }
  );

  const loadInitialData = async () => {
    await Promise.all([loadRegions(), fetchOrganizations()]);
  };

  onMounted(() => {
    loadInitialData();
  });

  return {
    orgTableRef,
    regionTree,
    activeListTab,
    orgFilter,
    orgColumns,
    orgList,
    orgLoading,
    orgPagination,
    handleOrgSearch,
    handleOrgReset,
    handleOrgRowClick,
    handleOrgPageChange,
    handleOrgPageSizeChange,
    selectOrganization,
    organizationDrawerVisible,
    currentOrganization,
    closeOrganizationDetail,
    statusTagType,
    openCreateOrganization,
    openEditOrganization,
    removeOrganization,
    organizationModalVisible,
    organizationModalMode,
    editingOrganization,
    handleOrganizationModalSuccess,
    membersLoading,
    memberColumns,
    memberList,
    memberPagination,
    fetchMembers,
    handleMemberPageChange,
    handleMemberPageSizeChange,
    openMemberDialog,
    deleteMember,
    memberModalVisible,
    memberModalMode,
    editingMember,
    handleMemberModalSuccess,
    auditPendingLoading: pendingAuditLoading,
    auditRecordsLoading: auditRecordLoading,
    auditRecords,
    loadAuditRecords,
    handleAuditApprove,
    handleAuditReject,
    quickCreateVisible,
    handleQuickCreateSuccess,
    openQuickCreate,
    auditTableRef,
    auditFilter,
    auditColumns,
    auditList,
    auditPagination,
    flatRegionOptions,
    handleAuditSearch,
    handleAuditReset,
    handleAuditPageChange,
    handleAuditPageSizeChange,
    auditStatusTagType,
    auditDetailVisible,
    selectedAuditRecord,
    openAuditDetail,
    closeAuditDetail,
    approveAuditRecord,
    rejectAuditRecord
  };
}
